package com.bluefoxyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bluefoxyu.domain.dto.EnrollmentDTO;
import com.bluefoxyu.domain.dto.EnrollmentPageQueryDTO;
import com.bluefoxyu.domain.entity.Course;
import com.bluefoxyu.domain.entity.Enrollment;
import com.bluefoxyu.domain.entity.Student;
import com.bluefoxyu.domain.entity.Teacher;
import com.bluefoxyu.domain.result.PageResult;
import com.bluefoxyu.domain.vo.*;
import com.bluefoxyu.exception.BaseException;
import com.bluefoxyu.mapper.CourseMapper;
import com.bluefoxyu.mapper.EnrollmentMapper;
import com.bluefoxyu.mapper.TeacherMapper;
import com.bluefoxyu.service.IEnrollmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bluefoxyu.service.IStudentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 选课成绩表 服务实现类
 * </p>
 *
 * @author bluefoxyu
 * @since 2024-06-16
 */
@Service
public class EnrollmentServiceImpl extends ServiceImpl<EnrollmentMapper, Enrollment> implements IEnrollmentService {

    @Resource
    private EnrollmentMapper enrollmentMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private IStudentService studentService;
    @Resource
    private TeacherMapper teacherMapper;

    //统计每门课程的平均成绩、最高分、最低分
    @Override
    public EnrollmentVO getEnrollmentStatistics() {

        // 查询每门课程的平均成绩、最高分、最低分
        List<GradeStatistics> gradeStatisticsList = enrollmentMapper.selectStatistics();
        System.out.println("gradeStatisticsList = " + gradeStatisticsList);
        // 封装
        List<GradeStatisticsVO>gradeStatisticsVOList=new ArrayList<>();
        for (GradeStatistics gradeStatistics : gradeStatisticsList) {
            Integer courseId = gradeStatistics.getCourseId();
            // 封装
            GradeStatisticsVO gradeStatisticsVO = GradeStatisticsVO.builder()
                    .courseName(courseMapper.selectById(courseId).getName())
                    .avgScore(gradeStatistics.getAvgScore())
                    .maxScore(gradeStatistics.getMaxScore())
                    .minScore(gradeStatistics.getMinScore())
                    .build();
            gradeStatisticsVOList.add(gradeStatisticsVO);
        }
        // 返回结果

        return EnrollmentVO.builder()
                .gradeStatisticsVOList(gradeStatisticsVOList)
                .build();
    }

    @Override
    public List<StudentTotalGradeVO> getCreditByStudent() {

        List<StudentTotalGradeVO> studentTotalGradeVOList = new ArrayList<>();
        // 查询学生信息，并计算学分
        List<Student> studentList = studentService.list();
        for (Student student : studentList) {
            // 封装VO对象
            StudentTotalGradeVO studentTotalGradeVO = StudentTotalGradeVO.builder()
                    .id(student.getId())
                    .name(student.getName())
                    .studentId(student.getStudentId())
                    .totalCredits(studentService.selectStudentCredit(student.getId()))
                    .build();
            studentTotalGradeVOList.add(studentTotalGradeVO);
        }
        return studentTotalGradeVOList;
    }

    @Override
    public void AddCourse(EnrollmentDTO enrollmentDTO,Integer studentId) {

        // 根据学生id查询成绩表信息
        QueryWrapper<Enrollment>wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(Enrollment::getStudentId,studentId);
        List<Enrollment>enrollmentList=enrollmentMapper.selectList(wrapper);
        // 判断是否已经选过该课程
        for (Enrollment enrollment : enrollmentList) {
            if (enrollment.getCourseId().equals(enrollmentDTO.getCourseId())) {
                throw new BaseException("该学生已经选过该课程,请勿重复选课");
            }
        }
        // 封装
        Enrollment enrollment = Enrollment.builder()
                .courseId(enrollmentDTO.getCourseId())
                .studentId(studentId)
                .build();

        // 添加
        enrollmentMapper.insert(enrollment);
    }

    @Override
    public PageResult pageQuery(EnrollmentPageQueryDTO enrollmentPageQueryDTO) {

        //构建分页条件
        Page<Enrollment>page=Page.of(enrollmentPageQueryDTO.getPageNo(),enrollmentPageQueryDTO.getPageSize());

        //分页条件查询
        Page<Enrollment>p=lambdaQuery()
                .eq(enrollmentPageQueryDTO.getCourseId()!=null,
                        Enrollment::getCourseId,enrollmentPageQueryDTO.getCourseId())
                .page(page);

        List<EnrollmentPageVO> enrollmentPageVOList = new ArrayList<>();

        for (Enrollment enrollment : p.getRecords()) {

            System.out.println("enrollment = " + enrollment.getStudentId());

            Student student=studentService.getById(enrollment.getStudentId());
            Course course=courseMapper.selectById(enrollment.getCourseId());
            Teacher teacher=teacherMapper.selectById(course.getTeacherId());
            EnrollmentPageVO build = EnrollmentPageVO.builder()
                    .id(enrollment.getId())
                    .studentId(enrollment.getStudentId())
                    .studentName(student.getName())
                    .studentNumber(student.getStudentId())
                    .courseId(enrollment.getCourseId())
                    .courseName(course.getName())
                    .credits(course.getCredits())
                    .teacherId(course.getTeacherId())
                    .teacherName(teacher.getName())
                    .jobTitle(teacher.getJobTitle())
                    .grade(enrollment.getGrade())
                    .build();
            enrollmentPageVOList.add(build);
        }

        return new PageResult(p.getTotal(),p.getPages(),enrollmentPageVOList);
    }

}
